package org.idea.qiyu.framework.gateway.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * @Author linhao
 * @Date created in 8:14 上午 2022/4/13
 */
public class RestTemplateUtils {

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();


    public static void doRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpMethod httpMethod, String uri) {
        try {
            doDispatch(httpServletRequest, httpServletResponse, httpMethod, uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void doDispatch(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod, String uri) throws Exception {
        byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
        Object body = null;
        if (bodyBytes.length > 0) {
            body = new String(bodyBytes, StandardCharsets.UTF_8);
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            httpHeaders.add(name, request.getHeader(name));
        }
        if (request.getQueryString() != null && request.getQueryString().length() > 0) {
            uri = String.format(
                    "%s?%s",
                    uri,
                    URLDecoder.decode(request.getQueryString(), "utf-8"));
        }
        HttpEntity<Object> httpEntity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<WebResponse> exchange;
        exchange = REST_TEMPLATE.exchange(uri, httpMethod, httpEntity, WebResponse.class);
        response.setStatus(exchange.getStatusCodeValue());
        PrintWriter out = null;
        out = response.getWriter();
        out.write(com.alibaba.fastjson.JSON.toJSONString(exchange.getBody()));

    }
}
